/**
 * 易驰护运 - Recharge
 * http://menger.me
 * 充值
 * @桓桓
 */

'use strict';

import React from 'react'
import { StyleSheet, Text, TextInput, ScrollView, TouchableOpacity, ImageBackground, View, Keyboard } from 'react-native';
import {
    IconFont,
    ListView,
    VerticalLine,
    HorizontalLine,
    BannerComponent,
    HotNewsComponent,
    HomeResourceItem,
    ListHeaderLoading,
} from '../../components';
import * as WeChat from 'react-native-wechat-lib'
import { inject, observer } from 'mobx-react';

@inject('loginStore')
@observer
export default class Recharge extends React.Component {

    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            loading: true,
            price: 100,
            custom: '',
            priceType: 1, // 1:100 2: 500 3: 1000 4:自定义
            payType: 2, // 1支付宝 2微信
        };
    }

    componentDidMount() {
        this._addWeChatListener();
    }

    // 监听那个react-native-wechat-lib
    _addWeChatListener = async () => {
        let {onRefresh} = this.params;
        WeChat.addListener('PayReq.Resp', (res) => {
            if (res.errCode === 0) {
                ToastManager.message('支付成功!');
                onRefresh && onRefresh()
                RouterHelper.goBack();
            } else if (res.errCode === -1) {
                ToastManager.message('支付失败!');
            } else if (res.errCode === -2) {
                ToastManager.message('取消支付!');
            }
        });
    };

    onSubmit = async () => {
        let { price, payType } = this.state;
        let url = ServicesApi.PAY_CONTROLLER_RECHARGE;
        let data = {
            money: price,
            account_type: payType,
        };
        let result = await Services.post(url, data);
        if (result.code == StatusCode.SUCCESS_CODE) {
            this.onArousePayment(result.data)
        } else if (result.code === StatusCode.FAIL_CODE) {
            ToastManager.warn(result.msg);
        }
    }

    onArousePayment = async (data) => {
        let { onRefresh } = this.params;
        let { payType } = this.state;
        let type = '';
        if (payType === 1) {
            type = Constants.PAY_ALIPAY
        } else if (payType === 2) {
            type = Constants.PAY_WECHAT
        }
        let result = await PayManager.pay(type, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.message(result.msg);
            setTimeout(() => {
                onRefresh && onRefresh()
                RouterHelper.goBack()
            }, 1000);
        } else {
            ToastManager.message(result.msg);
        }
    }

    changePriceType = (type, text) => {
        if (type == 1) {
            this.refs.textInput1.blur();
            this.setState({ price: 100, priceType: 1 })
        } else if (type == 2) {
            this.refs.textInput1.blur();
            this.setState({ price: 500, priceType: 2 })
        } else if (type == 3) {
            this.refs.textInput1.blur();
            this.setState({ price: 1000, priceType: 3 })
        } else if (type == 4) {
            this.setState({ priceType: 4 })
        }
    }

    render() {
        let { dataSources, price, custom, priceType, payType } = this.state;
        return (
            <PageContainer style={styles.container}>
                <NavigationBar
                    title={'充值'}
                    style={[styles.navigationBarStyle]}
                />
                <ScrollView keyboardShouldPersistTaps={'handled'}>
                    <View style={styles.card}>
                        <View style={styles.cardTitle}>
                            <Text style={styles.title}>充值金额</Text>
                        </View>
                        <View style={styles.choicePrice}>
                            <TouchableOpacity style={[styles.choicePriceItem, priceType == 1 && { borderWidth: 0 }]} onPress={() => this.changePriceType(1)}>
                                {
                                    priceType == 1 &&
                                    <ImageView
                                        resizeMode={'cover'}
                                        style={styles.priceBackground}
                                        source={Images.img_price_background}
                                    />
                                }
                                <Text style={[styles.choicePriceItemText, priceType == 1 && { color: '#fff' }]}>充100元</Text>
                            </TouchableOpacity>

                            <TouchableOpacity style={[styles.choicePriceItem, priceType == 2 && { borderWidth: 0 }]} onPress={() => this.changePriceType(2)}>
                                {
                                    priceType == 2 &&
                                    <ImageView
                                        resizeMode={'cover'}
                                        style={styles.priceBackground}
                                        source={Images.img_price_background}
                                    />
                                }
                                <Text style={[styles.choicePriceItemText, priceType == 2 && { color: '#fff' }]}>充500元</Text>
                            </TouchableOpacity>

                            <TouchableOpacity style={[styles.choicePriceItem, priceType == 3 && { borderWidth: 0 }]} onPress={() => this.changePriceType(3)}>
                                {
                                    priceType == 3 &&
                                    <ImageView
                                        resizeMode={'cover'}
                                        style={styles.priceBackground}
                                        source={Images.img_price_background}
                                    />
                                }
                                <Text style={[styles.choicePriceItemText, priceType == 3 && { color: '#fff' }]}>充1000元</Text>
                            </TouchableOpacity>

                            <View style={[styles.choicePriceItem, priceType == 4 && { borderWidth: 0 }]}>
                                {
                                    priceType == 4 &&
                                    <ImageView
                                        resizeMode={'cover'}
                                        style={styles.priceBackground}
                                        source={Images.img_price_background}
                                    />
                                }
                                <TextInput
                                    ref="textInput1"
                                    defaultValue={custom}
                                    style={[styles.choicePriceItemInput, priceType == 4 && { color: '#fff' }]}
                                    placeholder={'自定义输入'}
                                    placeholderTextColor={'#999'}
                                    onFocus={() =>
                                        this.changePriceType(4)
                                    }
                                    onChangeText={(text) => this.setState({ custom: text })}
                                />
                            </View>
                        </View>
                    </View>
                    <View style={styles.card}>
                        <View style={styles.cardTitle}>
                            <Text style={styles.title}>选择支付方式</Text>
                        </View>
                        {/* <TouchableOpacity style={styles.payTypeLine} onPress={() => this.setState({ payType: 1 })}>
                            <ImageView
                                resizeMode={'contain'}
                                style={styles.payTypeImg}
                                source={Images.icon_alipay_logo}
                            />
                            <Text style={styles.payTypeText}>支付宝</Text>
                            <TouchableOpacity style={[styles.payTypeRadio, payType == 1 && { borderColor: '#00BFCC' }]}>
                                {payType == 1 && <View style={styles.payTypeRadioBall} />}
                            </TouchableOpacity>
                        </TouchableOpacity> */}
                        <TouchableOpacity style={styles.payTypeLine} onPress={() => this.setState({ payType: 2 })}>
                            <ImageView
                                resizeMode={'contain'}
                                style={styles.payTypeImg}
                                source={Images.icon_wechat_logo}
                            />
                            <Text style={styles.payTypeText}>微信支付</Text>
                            <TouchableOpacity style={[styles.payTypeRadio, payType == 2 && { borderColor: '#00BFCC' }]}>
                                {payType == 2 && <View style={styles.payTypeRadioBall} />}
                            </TouchableOpacity>
                        </TouchableOpacity>
                        <Button
                            style={styles.btn}
                            title={'充值'}
                            titleStyle={styles.btnTitle}
                            resizeMode={'cover'}
                            backgroundImage={Images.img_btn_bg1}
                            onPress={() => this.onSubmit()}
                        />
                    </View>
                </ScrollView>
            </PageContainer>
        );
    }
}

const DominantColor = '#00BFCC';
const styles = StyleSheet.create({
    container: {
        backgroundColor: '#F0F0F0'
    },

    card: {
        backgroundColor: '#fff',
        marginBottom: 10,
        paddingLeft: 15,
    },
    cardTitle: {
        height: 40,
        justifyContent: 'center',
    },
    title: {
        fontSize: 13,
        color: '#333',
        fontWeight: 'bold',
    },
    choicePrice: {
        flexDirection: 'row',
        flexWrap: 'wrap',
    },
    choicePriceItem: {
        width: SCREEN_WIDTH / 2 - 22.5,
        height: 60,
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: DominantColor,
        borderRadius: 10,
        marginRight: 15,
        marginBottom: 15,
        overflow: 'hidden',
    },
    priceBackground: {
        width: '100%',
        height: '100%',
        position: 'absolute',
    },
    choicePriceItemText: {
        fontSize: 12,
        color: DominantColor,
    },
    choicePriceItemInput: {
        color: DominantColor,
        fontSize: 12,
        height: 60,
        width: '100%',
        textAlign: 'center',
    },

    payTypeLine: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 40,
        marginRight: 15,
    },
    payTypeImg: {
        width: 20,
        height: 20,
        marginRight: 10,
    },
    payTypeText: {
        fontSize: 12,
        fontWeight: 'bold',
        color: '#333',
        flex: 1,
    },
    payTypeRadio: {
        width: 16,
        height: 16,
        borderRadius: 8,
        borderWidth: 2,
        borderColor: '#e1e1e1',
        justifyContent: 'center',
        alignItems: 'center',
    },
    payTypeRadioBall: {
        width: 8,
        height: 8,
        borderRadius: 4,
        backgroundColor: DominantColor,
    },

    btn: {
        backgroundColor: DominantColor,
        width: SCREEN_WIDTH - 30,
        marginVertical: 15,
    },
});